import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Connection, Repository } from 'typeorm'
import { User } from '../entity/User'
import { BusinessException } from 'src/common/exceptions/business.exception'
import { UserInfo } from 'src/entity/Userinfo'

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private connection: Connection,
  ) { }

  // userName -> *
  async findOne(userName: string): Promise<User> {
    if (!userName) throw new BusinessException('参数错误')
    const sqlUserData = await this.usersRepository.findOne({
      where: { userName: userName },
    })
    if (sqlUserData?.isDelete) throw new BusinessException('该账号已经注销')
    await this.connection.transaction(async (manager) => {
      const sqlData = await manager.findOne(UserInfo, {
        where: {
          userName,
          disable: true,
        },
      })
      if (sqlData) throw new BusinessException('该账号被禁止使用')
    })
    return sqlUserData
  }
}
